<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="名称" prop="familyName">
          <el-input v-model="queryParams.familyName" placeholder="名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="所属区域" prop="areaCode">
          <el-popover ref="searchPopoverRef" placement="bottom-start" :width="400" trigger="click"
            popper-class="custom-tree-select-popover">
            <template #reference>
              <el-input v-model="searchSelectedAreaName" placeholder="请选择所在区域" :disabled="false" :readonly="false"
                style="width: 400px;" @click="() => searchPopoverRef.value.show()" clearable
                @clear="clearSearchSelection">
              </el-input>
            </template>
            <div class="tree-container">
              <el-tree ref="searchTreeRef" :data="regionOptions" node-key="areaCode" :props="{
                isLeaf: (data) => data.level === 5,
                label: 'name',
                children: 'children',
                level: 'level',
              }" :load="loadRegionNodes" lazy @node-click="handleSearchNodeClick" />
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增的el-card表格元素 -->
    <el-card shadow="never" class="related-family-card">
      <template #header>
        <div class="card-header">
          <span>我的家谱信息</span>
        </div>
      </template>
      <div class="mb-10px">
        <el-button v-if="total == 0" type="success" icon="plus"
          @click="handleOpenDialog()">
          新增
        </el-button>
        <el-button v-hasPerm="['genealogy:family:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          删除
        </el-button>
      </div>
      <el-table :data="pageData" style="width: 100%" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="家谱ID" prop="id" min-width="150" align="center" />
        <el-table-column key="familyName" label="家谱名称11" prop="familyName" min-width="150" align="center" />
        <el-table-column key="mergerName" label="行政区划" prop="mergerName" min-width="150" align="center" />
        <el-table-column key="originPlace" label="家谱发源地" prop="originPlace" min-width="150" align="center" />
        <el-table-column key="totem" label="家谱图腾" prop="totem" min-width="150" align="center" />
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="150" align="center" />
        <el-table-column key="updateTime" label="更新时间" prop="updateTime" min-width="150" align="center" />

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-col>
              <el-button v-hasPerm="['genealogy:family:edit']" v-if="userFamilyId == scope.row.id" type="primary"
                size="small" link @click="handleOpenDialog(scope.row.id)">
                <template #icon>
                  <Edit />
                </template>
                编辑
              </el-button>
            </el-col>
            <el-col>
              <el-button v-hasPerm="['genealogy:family:edit']" v-if="baseFlag == 1" type="primary" size="small" link
                @click="handleOpenDialog1(scope.row.id)">
                <template #icon>
                  <Edit />
                </template>
                修缮家谱
              </el-button>
            </el-col>
            <el-col>
              <el-button v-if="baseFlag != 1" :type="scope.row.activedStatus === 1 ? 'success' :
                  scope.row.joinStatus === 1 ? 'info' :
                    scope.row.joinStatus === 0 ? 'warning' :
                      scope.row.joinStatus === 2 ? 'danger' : 'primary'
                " size="small" link @click="joinFamily(scope.row.id)">
                <template #icon>
                  <Edit />
                </template>
                {{
                  scope.row.activedStatus === 1 ? "查看家谱" :
                    scope.row.joinStatus === 1 ? "等待入谱" :
                      scope.row.joinStatus === 0 ? "审核中" :
                        scope.row.joinStatus === 2 ? '被拒绝' : "加入家谱"
                }}
              </el-button>
            </el-col>
            <el-col>
              <el-button v-hasPerm="['genealogy:family:delete']" type="danger" size="small" link
                @click="handleDelete(scope.row.id)">
                <template #icon>
                  <Delete />
                </template>
                删除
              </el-button>
            </el-col>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>家谱列表</span>
        </div>
      </template>
      <el-table ref="dataTableRef" :data="pageDataList" highlight-current-row row-key="id" border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="家谱ID" prop="id" min-width="150" align="center" />
        <el-table-column key="familyName" label="家谱名称11" prop="familyName" min-width="150" align="center" />
        <el-table-column key="mergerName" label="行政区划" prop="mergerName" min-width="150" align="center" />
        <el-table-column key="originPlace" label="家谱发源地" prop="originPlace" min-width="150" align="center" />
        <el-table-column key="totem" label="家谱图腾" prop="totem" min-width="150" align="center" />
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="150" align="center" />
        <el-table-column key="updateTime" label="更新时间" prop="updateTime" min-width="150" align="center" />

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-col>
              <el-button v-hasPerm="['genealogy:family:edit']" v-if="userFamilyId == scope.row.id" type="primary"
                size="small" link @click="handleOpenDialog(scope.row.id)">
                <template #icon>
                  <Edit />
                </template>
                编辑
              </el-button>
            </el-col>
            <el-col>
              <el-button v-hasPerm="['genealogy:family:edit']" v-if="baseFlag == 1" type="primary" size="small" link
                @click="handleOpenDialog1(scope.row.id)">
                <template #icon>
                  <Edit />
                </template>
                修缮家谱
              </el-button>
            </el-col>
            <el-col>
              <el-button v-if="!scope.row.noTitle" :type="scope.row.activedStatus === 1 ? 'success' :
                  scope.row.joinStatus === 1 ? 'info' :
                    scope.row.joinStatus === 0 ? 'warning' :
                      scope.row.joinStatus === 2 ? 'danger' : 'primary'
                " size="small" link @click="joinFamily(scope.row.id)">
                <template #icon>
                  <Edit />
                </template>
                {{
                  scope.row.activedStatus === 1 ? "查看家谱" :
                    scope.row.joinStatus === 1 ? "等待入谱" :
                      scope.row.joinStatus === 0 ? "审核中" :
                        scope.row.joinStatus === 2 ? '被拒绝' : "加入家谱"
                }}
              </el-button>
            </el-col>
            <el-col>
              <el-button v-hasPerm="['genealogy:family:delete']" type="danger" size="small" link
                @click="handleDelete(scope.row.id)">
                <template #icon>
                  <Delete />
                </template>
                删除
              </el-button>
            </el-col>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="totalList > 0" v-model:total="totalList" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 家谱信息表单弹窗 -->
    <el-drawer v-model="dialog.visible" :title="dialog.title" :size="drawerSize" @close="handleCloseDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="家谱名称" prop="familyName">
          <el-input v-model="formData.familyName" placeholder="家谱名称" />
        </el-form-item>

        <el-form-item label="家谱发源地" prop="originPlace">
          <el-input v-model="formData.originPlace" placeholder="家谱发源地" />
        </el-form-item>
        <el-form-item label="行政区划" prop="areaCode">
          <el-popover ref="formPopoverRef" placement="bottom-start" :width="400" trigger="click"
            popper-class="custom-tree-select-popover">
            <template #reference>
              <el-input v-model="formSelectedAreaName" placeholder="请选择行政区划" :disabled="false" :readonly="false"
                style="width: 100%;" @click="() => formPopoverRef.value.show()" clearable @clear="clearFormSelection">
              </el-input>
            </template>
            <div class="tree-container">
              <el-tree ref="formTreeRef" :data="regionOptions" node-key="areaCode" :props="{
                isLeaf: (data) => data.level === 5,
                label: 'name',
                children: 'children',
                level: 'level',
              }" :load="loadRegionNodes" lazy @node-click="handleFormNodeClick" />
            </div>
          </el-popover>
        </el-form-item>

        <el-form-item label="家谱图腾" prop="totem">
          <el-input v-model="formData.totem" placeholder="家谱图腾" />
        </el-form-item>

        <el-form-item label="加入码" prop="joinCode">
          <el-input v-model="formData.joinCode" placeholder="加入码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 申请理由对话框 -->
    <el-drawer v-model="joinReasonDialog.visible" :title="joinReasonDialog.title" :size="drawerSize"
      @close="closeJoinReasonDialog">
      <el-form ref="joinReasonFormRef" :model="joinReasonForm" :rules="joinReasonRules" label-width="100px">
        <el-form-item label="申请说明" prop="reason">
          <el-input v-model="joinReasonForm.reason" type="textarea" :rows="2" maxlength="100"
            placeholder="请简要说明申请加入的原因" />
        </el-form-item>

        <!-- 家谱树可视化编辑部分 -->
        <div class="family-tree-section">
          <div class="section-header">
            <h3>家谱关系图</h3>
          </div>

          <!-- 使用简易家谱树组件 -->
          <div class="family-tree-container">
            <SimpleFamilyTree v-model="familyTreeData" :current-user-id="currentMemberId" title="家庭成员关系图"
              @node-click="handleFamilyNodeClick" />
          </div>
        </div>

        <div class="el-form-item-tip">
          <el-alert title="提示：请在家谱树中添加父辈、本人等重要家庭成员信息" type="warning" :closable="false" show-icon />
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitJoinApplication()">提交申请</el-button>
          <el-button @click="closeJoinReasonDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 支付指标消耗弹窗 -->
    <el-drawer v-model="paymentDialog.visible" :title="paymentDialog.title" :size="drawerSize"
      @close="closePaymentDialog">
      <el-form ref="paymentFormRef" :model="paymentForm" :rules="paymentRules" label-width="100px">
        <div v-if="waitingMembers.length > 0">
          <div class="waiting-members-section">
            <div class="section-header">
              <h3>待入谱成员列表 (共{{ totalMembersCount }}人)</h3>
            </div>
            <el-table :data="waitingMembers" style="width: 100%">
              <el-table-column prop="name" label="姓名" width="120"></el-table-column>
              <el-table-column prop="gender" label="性别" width="80">
                <template #default="scope">
                  {{ scope.row.gender === 1 ? '男' : '女' }}
                </template>
              </el-table-column>
              <el-table-column prop="alive" label="状态" width="80">
                <template #default="scope">
                  {{ scope.row.alive === 1 ? '在世' : '已故' }}
                </template>
              </el-table-column>
              <el-table-column prop="relation" label="与申请人关系">
                <template #default="scope">
                  <el-tag v-if="scope.row.isSelf" type="success">本人</el-tag>
                  <span v-else>{{ scope.row.relation }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-alert type="info" :closable="false" show-icon title="提示"
            :description="`每位成员入谱需消耗1个指标，总计需要消耗指标数量：${totalMembersCount}个`" style="margin: 15px 0" />
        </div>
        <el-form-item label="消耗指标">
          <div class="quota-display">
            <el-tag size="large" type="success">{{ totalMembersCount }}个</el-tag>
            <span class="quota-text">将消耗{{ totalMembersCount }}个指标用于入谱</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPayment()">确认入谱</el-button>
          <el-button @click="closePaymentDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 关联家谱弹窗 -->
    <div v-if="relatedFamilyList.length > 0 || relatedFamilyLoading" class="related-family-list-section"
      style="padding: 20px 0; padding-left: 20px; padding-right: 20px;">
      <h3>关联家谱列表</h3>
      <el-table :data="relatedFamilyList" v-loading="relatedFamilyLoading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="sourceFamilyName" label="源家谱" />
        <el-table-column prop="targetFamilyName" label="目标家谱" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="info">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger">已拒绝</el-tag>
            <el-tag v-else>未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditRemark" label="备注" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" link
              @click="router.push({ path: '/genealogy/family/detail', query: { id: scope.row.targetFamilyId } })">
              <template #icon>
                <Edit />
              </template>
              查看家谱
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from "vue";
import FamilyAPI from "@/api/genealogy/family.api";
import { ElMessage, ElMessageBox } from "element-plus";
import { DeviceEnum } from "@/enums/index.js";
import { useAppStore, useUserStore, usePermissionStore } from "@/store";
import router from "@/router";
import RegionAPI from "@/api/system/region.api.js";
import AuthAPI from "@/api/auth.api";
import { getAccessToken, setRefreshToken, setAccessToken } from "@/utils/auth";
import SimpleFamilyTree from "@/components/FamilyTree/SimpleFamilyTree.vue";
import { Plus, Delete, Edit, Close, Link } from '@element-plus/icons-vue';
import UserAPI from "@/api/system/user.api";
import PersonAPI from "@/api/genealogy/person.api";

const searchPopoverRef = ref(null);
const formPopoverRef = ref(null);
const appStore = useAppStore();
const userStore = useUserStore();
const PermissionStore = usePermissionStore();
const { userFamilyId, baseFlag } = useUserStore().userInfo;
const searchTreeRef = ref(null);
const formTreeRef = ref(null);
const formSelectedAreaName = ref("");

defineOptions({
  name: "Family",
  inheritAttrs: false,
});
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));
const queryFormRef = ref();
const searchSelectedAreaName = ref("");
const dataFormRef = ref();
const joinReasonFormRef = ref();
const paymentFormRef = ref();
const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const totalList = ref(0)
// 顶级行政区划下拉选项
const regionOptions = ref([]);
const queryParams = reactive({
  familyName: "",
  pageNum: 1,
  pageSize: 10,
});

// 家谱信息表格数据
const pageData = ref([]);
const pageDataList = ref([]);
// 弹窗
const dialog = reactive({
  title: "新增家谱",
  visible: false,
});

// 初始行政区划表单数据
const initialFormData = ref({
  id: undefined,
  familyName: "",
  originPlace: "",
  totem: "",
});
// 家谱信息表单数据
const formData = ref({ ...initialFormData.value });

// 家谱信息表单校验规则
const rules = reactive({
  familyName: [{ required: true, message: "请输入家谱名称", trigger: "blur" }],
  originPlace: [{ required: true, message: "请输入发源地", trigger: "blur" }],
  areaCode: [{ required: true, message: "请输入行政区划", trigger: "blur" }],
  totem: [{ required: true, message: "请输入图腾/象征", trigger: "blur" }],
});

// 存储树选择组件的节点数据
const treeNodeMap = ref(new Map());

// 申请理由对话框
const joinReasonDialog = reactive({
  title: "申请加入家谱",
  visible: false,
});

// 支付指标消耗弹窗
const paymentDialog = reactive({
  visible: false,
  familyId: null,
  title: "确认入谱"
});

// 支付表单数据
const paymentForm = ref({
  index: 1
});

// 支付表单校验规则
const paymentRules = reactive({
  index: [
    { required: true, message: "请输入消耗指标数量", trigger: "blur" },
    { type: "number", min: 1, message: "指标数量必须大于0", trigger: "blur", transform: val => Number(val) }
  ]
});

// 申请理由表单数据
const joinReasonForm = ref({
  familyId: null,
  reason: '',
  familyData: null // 修改为存储整个家谱树结构
});

// 申请理由表单校验规则
const joinReasonRules = reactive({
  reason: [{ required: true, message: "请输入申请说明", trigger: "blur" }]
});

// 家谱树数据
const familyTreeData = ref({
  id: Date.now().toString(),
  firstName: '',
  lastName: '',
  gender: 1,
  isAlive: true,
  isSelf: true
});

// 当前成员ID（默认为自己）
const currentMemberId = ref(familyTreeData.value.id);

// 待入谱成员列表
const waitingMembers = ref([]);
// 待入谱成员总数
const totalMembersCount = ref(0);

// 关联家谱弹窗相关状态
const relatedFamilyDialogVisible = ref(false);
const relatedFamilyList = ref([]);
const relatedFamilyLoading = ref(false);

// 处理家谱树节点点击
function handleFamilyNodeClick(node, type) {
  // 不再需要转换，直接使用家谱树数据
  console.log('节点被点击:', node, type);
}

// 不再需要从家谱树数据中提取成员信息，直接使用树结构
function updateFamilyMembersFromTree() {
  // 直接将整个家谱树结构赋值给表单数据
  joinReasonForm.value.familyData = familyTreeData.value;
}

// 显示申请理由对话框
function showJoinReasonDialog(familyId) {
  joinReasonDialog.visible = true;
  joinReasonForm.value.familyId = familyId;

  // 初始化家谱树数据
  familyTreeData.value = {
    id: Date.now().toString(),
    firstName: '我的',
    lastName: '姓氏',
    gender: 1,
    isAlive: true,
    isSelf: true
  };
  currentMemberId.value = familyTreeData.value.id;
}

// 提交加入家谱申请
function submitJoinApplication() {
  joinReasonFormRef.value.validate((valid) => {
    if (valid) {
      // 直接使用家谱树数据
      joinReasonForm.value.familyData = familyTreeData.value;

      // 检查家谱树数据是否有效
      if (!joinReasonForm.value.familyData) {
        ElMessage.warning("请添加家庭成员信息");
        return;
      }

      // 检查是否包含本人信息
      const hasSelf = checkSelfInTree(joinReasonForm.value.familyData);
      if (!hasSelf) {
        ElMessage.warning("请添加本人信息");
        return;
      }

      loading.value = true;

      FamilyAPI.join({
        familyId: joinReasonForm.value.familyId,
        reason: joinReasonForm.value.reason,
        familyData: joinReasonForm.value.familyData // 直接传递家谱树数据
      })
        .then(() => {
          ElMessage.success("申请加入成功,待审核!");
          handleQuery();
          closeJoinReasonDialog();
        })
        .catch((error) => {
          console.error("加入家谱失败:", error);
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 检查树中是否包含本人信息
function checkSelfInTree(node) {
  if (!node) return false;

  if (node.isSelf) return true;

  // 检查子节点
  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      if (checkSelfInTree(child)) return true;
    }
  }

  // 检查配偶
  if (node.spouseList && node.spouseList.length > 0) {
    for (const spouse of node.spouseList) {
      if (spouse.isSelf) return true;
    }
  }

  return false;
}

// 查询参数示例
const queryParamsFamily = {
  familyId: "7"
  // 其它筛选条件
};

PersonAPI.getFamilyJoinListByFamilyId(queryParamsFamily).then(res => {
  // 处理返回数据
  console.log(res);
});

// 关闭申请理由对话框
function closeJoinReasonDialog() {
  joinReasonDialog.visible = false;
  joinReasonForm.value = {
    familyId: null,
    reason: '',
    familyData: null // 修改为存储整个家谱树结构
  };
  joinReasonFormRef.value?.resetFields();

  // 清空家谱树数据
  familyTreeData.value = {
    id: Date.now().toString(),
    firstName: '',
    lastName: '',
    gender: 1,
    isAlive: true,
    isSelf: true
  };
}

/** 查询家谱信息 */
function handleQuery() {
  loading.value = true;

  let queryMethod;
  queryMethod = FamilyAPI.getPage;

  queryMethod(queryParams)
    .then(async (data) => {
      const flag = pageData.value.length;
      data.list.forEach(item => {
        if(flag && item.activedStatus !== 1) {
          item['noTitle'] = true;
        } else {
          item['noTitle'] = false;
        }
      });
      console.log(data.list)
      pageDataList.value = data.list;
      totalList.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 加入家谱信息 */
function joinFamily(familyId) {

  // 根据当前数据判断是否已加入
  const currentFamily = pageDataList.value.find((item) => item.id === familyId);

  if (currentFamily) {
    if (currentFamily.activedStatus === 1) {
      // 已加入，查看家谱
      router.push({ name: "Person", params: { familyId: familyId } });
    } else if (currentFamily.joinStatus === 1) {
      // 等待入谱，显示支付弹窗
      showPaymentDialog(familyId);
    } else if (currentFamily.joinStatus === 0) {
      // 审核中
      ElMessage.info("您的加入申请正在审核中，请耐心等待");
    } else if (currentFamily.joinStatus === 2) {
      // 被拒绝，显示拒绝理由，可重新申请
      const rejectReason = currentFamily.reason || "未提供拒绝理由";
      ElMessageBox.alert(
        `您的申请被拒绝，拒绝理由请查阅通知`,
        "申请被拒绝",
        {
          confirmButtonText: "重新申请",
          type: "error",
          callback: (action) => {
            if (action === "confirm") {
              showJoinReasonDialog(familyId);
            }
          }
        }
      );
    } else {
      // 未加入(null状态)，申请加入
      showJoinReasonDialog(familyId);
    }
  }
}

// 显示支付指标消耗弹窗
function showPaymentDialog(familyId) {
  paymentDialog.familyId = familyId;
  paymentDialog.visible = true;

  // 加载待入谱成员列表
  loading.value = true;
  FamilyAPI.getWaitForEnterFamily(familyId)
    .then((data) => {
      // 处理服务器返回的数据
      waitingMembers.value = data.memberApplyPersonList.map(member => {
        // 构建成员的显示名称（姓+名）
        const fullName = member.firstName + member.lastName;

        // 确定成员关系
        let relation = '';
        if (member.isSelf === 1) {
          relation = '本人';
        } else if (member.flag === 1) {
          relation = '配偶';
        } else {
          // 查找父亲
          const parent = data.memberApplyPersonList.find(p => p.id === member.parentId);
          if (parent) {
            const parentName = parent.firstName + parent.lastName;
            relation = `${parentName}的${member.gender === 1 ? '儿子' : '女儿'}`;
          } else {
            relation = member.gender === 1 ? '男性亲属' : '女性亲属';
          }
        }

        return {
          id: member.id,
          name: fullName,
          gender: member.gender,
          alive: member.alive,
          relation: relation,
          isSelf: member.isSelf === 1
        };
      });

      // 设置总成员数
      totalMembersCount.value = data.num || waitingMembers.value.length;

      // 固定消耗指标数量为成员总数
      paymentForm.value.index = totalMembersCount.value;
    })
    .catch((error) => {
      console.error("获取待入谱成员失败:", error);
      ElMessage.error("获取待入谱成员失败");
    })
    .finally(() => {
      loading.value = false;
    });
}

// 提交指标消耗
function submitPayment() {
  loading.value = true;
  // 先获取用户额度
  UserAPI.getProfile()
    .then((profile) => {
      const availableQuota = profile.availableQuota || 0;
      if (availableQuota < totalMembersCount.value) {
        // 额度不足，提示并跳转
        ElMessageBox.confirm(
          "您的可用指标额度不足，请前往购买。",
          "额度不足",
          {
            confirmButtonText: "去购买",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          // 跳转到购买页面（路由名为 userRecharge
          router.push({ name: "UserRecharge" });
        });
        loading.value = false;
        return;
      }
      // 额度足够，继续入谱
      FamilyAPI.doEnterFamily(paymentDialog.familyId)
        .then(() => {
          ElMessage.success("入谱成功，所有成员已加入家谱！");
          handleQuery();
          closePaymentDialog();
        })
        .catch((error) => {
          console.error("入谱失败:", error);
          ElMessage.error("入谱失败，请检查指标余额是否充足");
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch((error) => {
      loading.value = false;
      ElMessage.error("获取用户额度失败");
    });
}

// 关闭支付指标消耗弹窗
function closePaymentDialog() {
  paymentDialog.visible = false;
  paymentDialog.familyId = null;
  paymentForm.value = { index: 1 };
  waitingMembers.value = [];
  totalMembersCount.value = 0;
  paymentFormRef.value?.resetFields();
}

/** 重置家谱信息查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  FamilyAPI.getMyPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

/** 打开家谱信息弹窗 */
function handleOpenDialog(id) {
  // 初始化只加载省级数据
  RegionAPI.getOptions({ type: 0, areaCode: 0 })
    .then((data) => {
      regionOptions.value = data;
      // 存储初始节点数据
      data.forEach(item => {
        treeNodeMap.value.set(item.areaCode, item);
      });
    })
    .then(() => {
      dialog.visible = true;
      if (id) {
        dialog.title = "修改家谱信息";
        FamilyAPI.getFormData(id).then((data) => {
          Object.assign(formData.value, data);
          // 如果有区域代码，获取并显示区域名称
          if (formData.value.areaCode) {
            updateFormAreaName(formData.value.areaCode);
          }
        });
      } else {
        dialog.title = "新增家谱信息";
        formSelectedAreaName.value = "";
      }
    });
}

// 根据区域代码更新区域名称显示
function updateFormAreaName(areaCode) {
  if (!areaCode) return;

  // 如果已经有缓存的区域信息，直接使用
  if (treeNodeMap.value.has(areaCode)) {
    const node = treeNodeMap.value.get(areaCode);
    formSelectedAreaName.value = node.name;
    return;
  }

  // 否则请求区域详情
  RegionAPI.getDetail(areaCode).then(data => {
    if (data && data.mergerName) {
      formSelectedAreaName.value = data.mergerName.replace(/,/g, " - ");
    }
  });
}

/** 打开家谱信息弹窗 */
async function handleOpenDialog1(id) {
  await new Promise(resolve => setTimeout(resolve, 100));
  router.push({ name: "Person", params: { familyId: id } });
}

/** 提交家谱信息表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const id = formData.value.id;
      if (id) {
        FamilyAPI.update(id, formData.value)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        FamilyAPI.create(formData.value)
          .then(() => {
            AuthAPI.refreshToken(getAccessToken()).then((data) => {
              setAccessToken(data.accessToken);
              setRefreshToken(data.refreshToken);
              useUserStore().userInfo = userStore.getUserInfo();
              // 重新加载路由以反映权限变化
              PermissionStore.resetRouter();
              PermissionStore.generateRoutes().then((dynamicRoutes) => {
                dynamicRoutes.forEach((route) => router.addRoute(route));
              });
              handleResetQuery();
            });
            ElMessage.success("新增成功");
            handleCloseDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭家谱信息弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.value = { ...initialFormData.value };
  formSelectedAreaName.value = "";
  if (formTreeRef.value) {
    formTreeRef.value.setCurrentKey(null);
  }
}

/** 删除家谱信息 */
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      FamilyAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 懒加载行政区划节点
function loadRegionNodes(node, resolve) {
  if (node.level === 0) {
    // 根节点，已在初始化时加载省级数据
    return resolve(regionOptions.value);
  }

  // 根据当前节点级别确定请求的type值
  const type = node.level;
  // 使用当前节点的areaCode作为请求参数
  const areaCode = node.data.areaCode;

  RegionAPI.getOptions({ type, areaCode })
    .then(data => {
      // 返回子节点数据
      // 存储所有加载的节点数据，用于后续查询
      data.forEach(item => {
        treeNodeMap.value.set(item.areaCode, item);
      });
      resolve(data);
    })
    .catch(() => {
      resolve([]);
    });
}

function handleSearchNodeClick(data, node) {
  if (data.level === 5) {
    queryParams.areaCode = data.areaCode;
    let currentNode = node;
    let pathNames = [];
    while (currentNode && currentNode.level > 0) {
      pathNames.unshift(currentNode.label);
      currentNode = currentNode.parent;
    }
    searchSelectedAreaName.value = pathNames.join(" - ");
    searchPopoverRef.value.hide();
  }
}

function clearSearchSelection() {
  queryParams.areaCode = null;
  searchSelectedAreaName.value = "";

  // 重置树组件的选中状态
  if (searchTreeRef.value) {
    searchTreeRef.value.setCurrentKey(null);
  }

  // 触发重新查询
  handleQuery();
}

function handleFormNodeClick(data, node) {
  if (data.level === 5) {
    formData.value.areaCode = data.areaCode;
    let currentNode = node;
    let pathNames = [];
    while (currentNode && currentNode.level > 0) {
      pathNames.unshift(currentNode.label);
      currentNode = currentNode.parent;
    }
    formSelectedAreaName.value = pathNames.join(" - ");
    formPopoverRef.value.hide();
  }
}

function clearFormSelection() {
  formData.value.areaCode = null;
  formSelectedAreaName.value = "";

  // 重置树组件的选中状态
  if (formTreeRef.value) {
    formTreeRef.value.setCurrentKey(null);
  }
}

// 查看关联家谱按钮点击事件
async function handleViewRelatedFamily(familyId) {
  relatedFamilyDialogVisible.value = true;
  relatedFamilyLoading.value = true;
  try {
    const res = await PersonAPI.getFamilyJoinListByFamilyId({ 'familyId': '7' });
    relatedFamilyList.value = res.list || [];
  } catch (e) {
    relatedFamilyList.value = [];
  } finally {
    relatedFamilyLoading.value = false;
  }
}

onMounted(() => {
  loading.value = true;
  FamilyAPI.getMyPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
      handleQuery();
    })
    .finally(() => {
      loading.value = false;
    });
  // 初始化只加载省级数据
  RegionAPI.getOptions({ type: 0, areaCode: 0 })
    .then((data) => {
      regionOptions.value = data;
      data.forEach((item) => {
        treeNodeMap.value.set(item.areaCode, item);
      });
    });
  handleViewRelatedFamily()
});
</script>

<style scoped>
.el-form-item-tip {
  margin-top: 8px;
}

/* 确保清除图标在输入框中显示 */
:deep(.el-input__clear) {
  display: inline-block !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.waiting-members-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 16px;
}

.quota-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quota-text {
  color: #606266;
  font-size: 14px;
}

.family-tree-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.related-family-list-section {
  background: #ffffff;
}

.family-tree-container {
  width: 100%;
  height: 400px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: #fff;
  overflow: hidden;
}

.tree-container {
  height: 500px;
  overflow: scroll;
}

.member-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #DCDFE6;
}

.member-index {
  font-weight: bold;
  color: #606266;
}

.name-input {
  width: 100%;
}

.relation-select {
  width: 100%;
}

:deep(.el-input-group__append) {
  padding: 0;
  background-color: transparent;
}
</style>
